<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/31
 * Time: 16:00
 */

namespace app\api\controller\android\v13;


use app\api\model\Common;
use app\api\model\User as UserModer;
use think\Cache;
use think\Controller;
use app\api\model\Authority;
use think\db;
use think\Request;
use app\api\model\OrderModel;
use think\Exception;

class User extends Controller {
    protected $model;
    protected $us;
    const  U_SRC = 'http://api.master.yiniao.cc/';
    
    public function _initialize() {
        $this->model = new Authority();
        $this->us    = $this->model->check(1);
    }
    
    /**
     * 修改手机号
     */
    public function reset_mobile() {
        $data = $this->model->post(['code', 'new_mobile']);
        if (!is_mobile($data['new_mobile'])) {
            r_date([], 300, '请输入正确的手机号');
        }
        $s_verify = Cache::get(md5($data['new_mobile']));
        if (empty($data['code']) || $data['code'] != $s_verify) {
            r_date([], 300, '验证码错误');
        }
        Cache::clear(md5($data['new_mobile']));
        $user = self::$user;
        if (db('user')->where(['mobile' => $data['new_mobile'], 'status' => ['in', '0,1,2']])->find()) {
            r_date([], 300, '该手机号已注册用户端，请重新选择手机号');
        }
        $res = db('user')->where(['user_id' => $user['user_id']])->update(['mobile' => $data['new_mobile']]);
        if ($res !== false) {
            r_date();
        }
        r_date([], 300, '修改失败，请刷新后重试');
    }

    /*
     *店长自动上线
     */
    public function automaticOnlineTime()
    {
        $data = Authority::param(['onlineTime']);
        $dispatch_config_user_auto = db('dispatch_config_user_auto', config('database.zong'))->where('user_id', $this->us['user_id'])->order('id desc')->find();
        if(!empty($dispatch_config_user_auto) && ($dispatch_config_user_auto['receive_priority'] == 1 || $dispatch_config_user_auto['receive_priority'] == 2)){
            r_date(null, 200, '修改成功');
        }
         db('user_online_time', config('database.zong'))->where('deleted_at', 0)->where(['user_id' => $this->us['user_id']])->update(['deleted_at' => time()]);
            if ($data['onlineTime'] != 0) {
                $data['onlineTime'] = $data['onlineTime'] / 1000;
                db('user_online_time', config('database.zong'))->insert(['user_id' => $this->us['user_id'], 'online_time' => strtotime(date('Y-m-d H:00:00', $data['onlineTime'])), 'created_time' => time(), 'city_id' => config('cityId')]);
                sendMsg($this->us['mobile'], 465347537, [date('Y-m-d H:00:00', $data['onlineTime'])]);
            }
        r_date(null, 200, '修改成功');
    }
    
    public function index(OrderModel $orderModel) {
        $retrun    = db('user')->join('store st', 'st.store_id=user.store_id', 'left')->field('user.user_id,user.work_tag,user.mobile,if(user.sales_or_deliverer=1,concat(user.username,"(销售)"),concat(user.username,"(交付)")) as username,user.avatar,user.sex,user.state,st.store_name,st.store_id,user.number,user.reserve,st.Inventory,user.sales_or_deliverer as deliverer,user.in_business as business')->where(['user_id' => $this->us['user_id']])->find();
        $starttime = strtotime(date('Y-m-01 00:00:00', time()));//获取指定月份的第一天
        $enttime   = strtotime(date('Y-m-t 23:59:59', time())); //获取指定月份的最后一天
        $quantity  = db('order')->join('order_times', 'order_times.order_id=order.order_id', 'left')->where(['order.assignor' => $this->us['user_id'], 'order_times.dispatch_time' => ['between', [$starttime, $enttime]]])->select();;//本月接单量
        $retrun['quantity']       = count($quantity);
        $user_online_time         = db('user_online_time', config('database.zong'))->where(['user_id' => $this->us['user_id'], 'city_id' => config('cityId')])->where('deleted_at', 0)->order('created_time desc')->find();
        $retrun['userOnlineTime'] = '';
        if (!empty($user_online_time)) {
            $retrun['userOnlineTime'] = date('m/d H:i', $user_online_time['online_time']);
        }
        $retrun['behaviorScore'] =  Db::connect(config('database.zong'))->table('behavior_score')->join('user', 'user.user_id=behavior_score.user_id', 'left')->where('user.ce', 1)->whereNotLike('user.username', "%代管%")->where('delete_time', 0)->where('behavior_score.user_id', $this->us['user_id'])->where('behavior_score.user_type', 1)->sum('behavior_score');
        $signing                 = (new ReserveWage())->RCalculatePerformance($this->us['user_id'], $starttime, $enttime, 1);
        $retrun['signing']       = empty($signing) ? 0 : $signing;
        $retrun['volume']        = (new Financial)->TurnoverRate('ss');
        $retrun['bankCard']      = \db('bank_card')->where(['user_id' => $this->us['user_id'], 'binding_uid' => $this->us['user_id']])->where('bank_card.delete_time', 0)->where('category', 1)->value('bank_card_number');
        $work_tag                = empty($retrun['work_tag']) ? [0, 0, 0, 0] : explode(',', $retrun['work_tag']);
        foreach ($work_tag as $k => $value) {
            $k = $k + 1;
            switch ($value) {
                case 0:
                    $value = 'https://images.yiniao.co/Icon/shopowner/small/' . $k . '-grey-small.png';
                    break;
                case 1:
                    $value = 'https://images.yiniao.co/Icon/shopowner/small/' . $k . '-small.png';
                    break;
            }
            $date[] = $value;
        }
        $retrun['work_tag'] = $date;
        $retrun['mobile']   = trim($retrun['mobile']);
        $retrun['pending']  = db('direct_order', config('database.zong'))->where('user_id', $this->us['user_id'])->where('type', 1)->where('state', 0)->count();
        if ($this->us['show_ranking'] == 1) {
//            $profit      = (new WorkBench())->Ranking(4, 2);
//            $achievement = (new WorkBench())->Ranking(1, 2);
//            $conversion  = (new WorkBench())->Ranking(2, 2);
//            $repurchase  = (new WorkBench())->Ranking(3, 2);
//            $retrun['profit']      = array_merge(arrayFilterFieldValue($profit, 'username', $this->us['username']))[0]['xu'] . "/" . count($profit);
//            $retrun['achievement'] = array_merge(arrayFilterFieldValue($achievement, 'username', $this->us['username']))[0]['xu'] . "/" . count($achievement);
//            $retrun['conversion']  = array_merge(arrayFilterFieldValue($conversion, 'username', $this->us['username']))[0]['xu'] . "/" . count($conversion);
//            $retrun['repurchase']  = array_merge(arrayFilterFieldValue($repurchase, 'username', $this->us['username']))[0]['xu'] . "/" . count($repurchase);
            $retrun['profit']      = "-/-";
            $retrun['achievement'] = "-/-";
            $retrun['conversion']  = "-/-";
            $retrun['repurchase']  = "-/-";
        } else {
            $retrun['profit']      = "-/-";
            $retrun['achievement'] = "-/-";
            $retrun['conversion']  = "-/-";
            $retrun['repurchase']  = "-/-";
            
        }
        r_date($retrun, 200, '获取成功');
    }
    
    public function Icon() {
        $work_tag = db('user')->where(['user_id' => $this->us['user_id']])->value('work_tag');
        $work_tag = empty($work_tag) ? [0, 0, 0, 0] : explode(',', $work_tag);
        foreach ($work_tag as $k => $value) {
            
            switch ($k) {
                case 0:
                    $data['title'] = '建筑渗漏水维修专家';
                    break;
                case 1:
                    $data['title'] = '旧房改造类专家';
                    break;
                case 2:
                    $data['title'] = '墙面维修专家';
                    break;
                case 3:
                    $data['title'] = '室内渗漏水维修专家';
                    break;
            }
            $k = $k + 1;
            switch ($value) {
                case 0:
                    $data['img'] = 'https://images.yiniao.co/Icon/shopowner/big/' . $k . '-grey.png';
                    break;
                case 1:
                    $data['img'] = 'https://images.yiniao.co/Icon/shopowner/big/' . $k . '.png';
                    break;
            }
            $date[] = $data;
        }
        
        
        r_date($date, 200, '获取成功');
    }
    
    /**
     * 修改我的状态
     */
    public function state()
    {
        $data = $this->model->post(['state']);

        //          if($data['state']==0){
        //              r_date(null, 300, '请注意，本次操作无效，离线状态需要联系城市总进行更改');
        //          }
        //店长在线时长统计
        $dispatch_config_user_auto = db('dispatch_config_user_auto', config('database.zong'))->where('user_id', $this->us['user_id'])->order('id desc')->find();
        if (($dispatch_config_user_auto['receive_priority'] == 1 || $dispatch_config_user_auto['receive_priority'] == 2) && $data['state'] == 0) {
            if ($dispatch_config_user_auto['receive_priority'] == 2) {
                $title = "次优先"; // 按你的业务规则来
            } else {
                $title = "优先";
            }
            r_date(null, 300, '因你的账号被商圈设置为' . $title . '接单账号，无法操作离线，若要离线请联系商圈经理在BI操作离线。');
        }
        db('online')->insertGetId(['user_id' => $this->us['user_id'], 'startTime' => time(), 'type' => $data['state'], 'time' => time()]);

        db('user')->where(['user_id' => $this->us['user_id']])->update(['state' => $data['state']]);
        if ($data['state'] == 1) {
            db('user_online_time', config('database.zong'))->where('deleted_at', 0)->where(['user_id' => $this->us['user_id']])->update(['deleted_at' => time()]);
        }

        r_date(null, 200);
    }
    
    /**
     * 修改我的状态
     */
    public function switchUser(UserModer $user) {
       
        $retrun = $user->Userlist($this->us['mobile']);
        
        r_date($retrun, 200);
    }
    /**
     * 万能账号列表
     */
    public function switchUserUniversal() {
        $retrun =  db('user', config('database.zong'))->field('user.user_id,user.mobile,if(user.sales_or_deliverer=1,concat(user.username,"(销售)"),concat(user.username,"(交付)")) as username,user.avatar,user.sex,user.access_token,st.store_name,user.reserve,user.sales_or_deliverer as deliverer,st.city,user.in_business')
            ->join('store st', 'user.store_id=st.store_id', 'left')
            ->where('user.status',0)
            ->where('user.ce',1)
            ->select();
        
        foreach ($retrun as $k =>$item){
            $retrun[$k]['city']=Common::city($item['city'])['city'];
            if($item['in_business']==2){
                $retrun[$k]['username']=$item['username']."(大改)";
            }
            if($item['in_business']==3){
                $retrun[$k]['username']=$item['username']."(小改)";
            }
        }
        r_date($retrun, 200);
    }
    public function switchUserMobel() {
      
        $valuess=db('sys_config', config('database.zong'))->where('statusss',1)->where('keyss','handover_user_mobel')->value('valuess');
        $date=[];
        if(!empty($valuess)){
            $date=explode(",",$valuess);
        }
         return $date;
    }
    /*
  * 交付店长列表
  */
    public function delivererList(UserModer $user) {
        $data   = Authority::param(['orderId']);
        $state  = \db('order')->where('order_id', $data['orderId'])->value('state');
        $retrun = null;
    //    $mobel=$this->switchUserMobel();
        if ($state <= 3) {
            r_date(null, 300, '转入施工后才能指派交付');
        } elseif ($state > 3 &&  $this->us['is_handover']==1) {
            $retrun = $user->UserDeliverer();
            r_date($retrun, 200);
        } else {
            r_date(null, 300, '你不是销售交付分离测试人员，无需指派');
        }
        
        
    }
    
    /**
     * 修改资料
     * invoice_type
     */
    public function edit() {
        $data = $this->model->post(['avatar']);
        $res  = db('user')->where(['user_id' => $this->us['user_id']])->update(['avatar' => $data['avatar'],]);
        if ($res !== false) {
            r_date([], 200);
        }
        r_date([], 300, '编辑失败，请刷新后重试');
    }
    
    
    public function Article() {
        $result = send_post(self::U_SRC . "/support/v1.article/all", []);
        
        
        r_date(json_decode($result, true), 200);
    }
    
    public function Article_list() {
        $data   = $this->model->post(['category_id', 'limit', 'page']);
        $result = send_post(self::U_SRC . "/support/v1.article/lists", $data);
        
        r_date(json_decode($result, true), 200);
    }
    
    /*
     * 免打扰
     */
    public function disturb() {
        $this->model->post(['type']);
        db('user')->where('user_id', $this->us['user_id'])->update(['disturb' => 2]);
        r_date([], 200);
    }
    
    /*
     * 获取地理位置
     */
    public function lat() {
        $data = $this->model->post(['lat', 'lng']);
        db('user')->where('user_id', $this->us['user_id'])->update(['lat' => $data['lat'], 'lng' => $data['lng']]);
        r_date(null, 200);
    }
    
    /*
     * 免打扰
     */
    public function about() {
        $da = db('about')->find();
        r_date($da, 200);
    }
    
    public function url() {
        $data = request()->post();
        if ($data['type'] == 2) {
            $da['url'] = config('faq') . '?type=1&uid=' . $this->us['user_id'] . '&url=' . $data['url'];
        } else {
            $da['url'] = 'https://www.yiniao.co/storemanage/index.html';
        }
        r_date($da, 200);
    }
    
    public function AppActivity() {
        $url = null;
        $advertisement_list = db('advertisement_list', config('database.zong'))->where('state',1)->where('app_type',1)->order('id desc')->find();
        $advertisement_count = db('advertisement_count', config('database.zong'))->where('user_id',$this->us['user_id'])->where('role',1)->where('ad_id',$advertisement_list['id'])->find();
        if (strpos($advertisement_list['url'], '?') !== false) {
            $link= $advertisement_list['url'].'&user_id='.$this->us['user_id'].'&user_name='.$this->us['username'].'&user_type=1&ad_id='.$advertisement_list['id'];
        } else {
            $link= $advertisement_list['url'].'?user_id='.$this->us['user_id'].'&user_name='.$this->us['username'].'&user_type=1&ad_id='.$advertisement_list['id'];
        }
        $url = [
            'link' =>  $link, 
            'img' => $advertisement_list['cover']
        ];
        if(($advertisement_list['end_time']<time() && $advertisement_list['ad_type'] ==1) || $advertisement_list['app_type'] !=1){
            $url = null;
        }
        if(($advertisement_list['count']<=$advertisement_count['view_count'] && $advertisement_list['ad_type'] ==2) || $advertisement_list['app_type'] !=1){
            $url = null;
        }
        if(($advertisement_count['task_state']==1 && $advertisement_list['ad_type'] ==3) || $advertisement_list['app_type'] !=1){
            $url = null;
        }
//        if(config('city') != 'cd'){
//            $url = [
//                'link' => 'https://api.shopowner.yiniao.cc/h5/#/',
//                'img' => 'https://images.yiniao.co/fang10.png',
//            ];
//        }else{
//            $url = [
//                'link' => 'https://api.shopowner.yiniao.cc/xin/#/',
//                'img' => 'https://images.yiniao.co/cd10.png',
//            ];
//        }
//        $id =$this->us['user_id'];
//        $key128 = '0123456789abcdef';
//        $iv = 'abcdef0123456789';
//        $encrypted = openssl_encrypt($id, 'aes-128-cbc', $key128, OPENSSL_RAW_DATA, $iv);
//        $url = [
//            'link' => 'http://syear.yiniao.cc/#/?type=1&i='.strtr(base64_encode($encrypted), '+/', '-_').'&city='.config('city'),
//            'img' => 'https://images.yiniao.co/20231228093740.png',
//        ];
        r_date($url, 200);
    }
    
    public function Applog() {
        $lm_applogs = db('lm_app_shopowner_version', config('database.bi'))->field("version,description,FROM_UNIXTIME(create_time,'%Y-%m-%d') as createTime")->order('id desc')->select();
        r_date($lm_applogs, 200);
    }
    
    public function UserMovable() {
        $user_movable = db('user_click')->where('user_id', $this->us['user_id'])->where('type', 1)->find();
        if ($user_movable) {
            db('user_click')->where('user_id', $this->us['user_id'])->where('type', 1)->update(['last_time' => time(), 'click_number' => $user_movable['click_number'] + 1]);
        } else {
            db('user_click')->insert(['last_time' => time(), 'create_time' => time(), 'click_number' => 1, 'user_id' => $this->us['user_id']]);
        }
        r_date(null, 200);
    }

    /*
     * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
     * 30  费用报销 31 主材费用报销，32返工费用报销 33 常规材料  34 采购材料  35 领用申请
     */
    public function message()
    {

        $message = db('message')->field('type,content,order_id,already,id')->where(['user_id' => $this->us['user_id']])->limit(0, 3)->orderRaw('already=1 desc,time desc')->select();
        $data    = [
            'data' => $message,
            'newOrders' => db('message')->where(['user_id' => $this->us['user_id'], 'type' => ['in', '2,3,4,6,45,60,61'], 'already' => 1])->count(), // 订单提醒
            'approval' => db('message')->where(['user_id' => $this->us['user_id'], 'type' => ['in', '30,31,32,33,34,35'], 'already' => 1])->count(), // 审批提醒
            //                  'Material'=>db('message')->where(['type'=>['in', '34,33'],'already'=>1, 'user_id'=>$this->us['user_id']])->count(),//
            'system' => db('message')->where(['type' => 1, 'already' => 1, 'user_id' => $this->us['user_id']])->count(), //系统消息
            'unread' => db('message')->where(['user_id' => $this->us['user_id'], 'already' => 1])->count(), //未读消息
            'conversation' => db('message')->where(['user_id' => $this->us['user_id'], 'already' => 1, 'type' => 42])->count(), //未读消息

        ];
        r_date($data, 200);
    }
    
    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_list() {
        //0全部1系统2订单3收款5公司通知7未读
        $data = $this->model->post(['type', 'page' => 1, 'limit' => 10, 'title']);
        $me   = db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content'] = ['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if ($data['type'] == 2) {
            $me->where(['type' => ['in', '3,4,6,45,51,60,61']]);
        } elseif ($data['type'] == 7) {
            $me->where(['already' => 1]);
        } elseif ($data['type'] == 5) {
            $me->where(['type' => $data['type']]);
        } elseif ($data['type'] == 1) {
            $me->where(['type' => $data['type']]);
        } elseif ($data['type'] == 22) {
            $me->where(['type' => ['in', '30,31,32']]);
        } elseif ($data['type'] == 23) {
            $me->where(['type' => ['in', '33,34,35,36,37']]);
        } elseif ($data['type'] == 42) {
            $me->where(['type' => ['in', '42']]);
        }
        $message = $me->where(['user_id' => $this->us['user_id']])->field('id,type,content,if(type=32,other_id,order_id) as order_id,already,other_id')->orderRaw('already=1 desc,time desc')->page($data['page'], $data['limit'])->select();
        foreach($message as  $k=>$item){
            $pattern = '/电话(\d{3})(\d{4})(\d{4})/';
            $replacement = '电话:$1****$3';
            // 替换电话号码
            $newText = preg_replace($pattern, $replacement, $item['content']);
            $message[$k]['content']=$newText;
            $messageInfo='';
            if($item['type']==61){
                $messageInfo=db('through')->where(['through_id' => $item['other_id']])->value('feedback');
            }
            $message[$k]['messageInfo']=$messageInfo; 
            
        }
        r_date($message, 200);
    }
    
    /*
     * 审批里面的类型
     */
    public function ApprovalType() {
        $data = $this->model->post(['type']);
        if ($data['type'] == 2) {
            $data = [['name' => '全部', 'type' => 0, 'jump' => 0,], ['name' => '订单提醒', 'type' => 2, 'jump' => 0,], ['name' => '收款预警提醒', 'type' => 45, 'jump' => 0,],['name' => '主材验收提醒', 'type' => 51, 'jump' => 0,],['name' => '邀约到店提醒', 'type' => 60, 'jump' => 0,]];
        } else {
            $data = [['name' => '全部', 'type' => 0, 'jump' => 0,], ['name' => '费用报销', 'type' => 30, 'jump' => 0,], ['name' => '主材费用报销', 'type' => 31, 'jump' => 0,], ['name' => '材料常规申请（常规）', 'type' => 33, 'jump' => 0,], ['name' => '返工费用报销', 'type' => 32, 'jump' => 0,], ['name' => '材料申请（采购）', 'type' => 34, 'jump' => 0,], ['name' => '材料领用', 'type' => 35, 'jump' => 0,], ['name' => '退款消息', 'type' => 37, 'jump' => 0,], ['name' => '大工地审批', 'type' => 36, 'jump' => 0,], ['name' => '特权订单', 'type' => 40, 'jump' => 0,], ['name' => '减项审批', 'type' => 41, 'jump' => 0,], ['name' => '供应链订单确认', 'type' => 50, 'jump' => 0,],['name' => '邀约到店提醒', 'type' => 60, 'jump' => 0,]
            
            ];
        }
        r_date($data, 200);
    }
    
    /*
   * /**30  费用报销 31 主材费用报销，32返工费用报销 33 常规材料  34 采购材料
     * 费用报销内容
     */
    
    public function message_listApproval() {
        
        $data = $this->model->post(['type', 'mainType', 'page', 'limit']);
        
        $me = db('message');
        if (isset($data['title']) && $data['title'] != '') {
            $map['content'] = ['like', "%{$data['title']}%"];
            $me->where($map);
        }
        if ($data['mainType'] == 2) {
            if ($data['type'] != 0) {
                if ($data['type'] == 2) {
                    $me->where(['type' => ['in', '3,4,6']]);
                } else {
                    $me->where(['type' => $data['type']]);
                }
                
            } else {
                $me->whereIn('type', [3, 4, 6, 2, 45,51,60,61]);
            }
        } else {
            if ($data['type'] != 0) {
                $me->where(['type' => $data['type']]);
            } else {
                $me->whereIn('type', [30, 31, 32, 33, 34, 35]);
            }
        }
        
        $message = $me->where(['user_id' => $this->us['user_id']])->field('id,type,content,order_id,already,FROM_UNIXTIME(time,"%Y-%m-%d %H:%i:%s"),other_id')->orderRaw('already=1 desc,time desc')->page($data['page'], $data['limit'])->select();
        foreach ($message as $k => $value) {
            if (!empty($value['order_id']) && $value['type'] == 45) {
                $order = db('order')->field('order.contacts,order.telephone,concat(p.province,c.city,y.county,order.addres) as addres,sum(payment.material+payment.agency_material) as sum,count(payment_id) as count')->join('user u', 'order.assignor=u.user_id', 'left')->join('province p', 'order.province_id=p.province_id', 'left')->join('city c', 'order.city_id=c.city_id', 'left')->join('county y', 'order.county_id=y.county_id', 'left')->join('payment', 'order.order_id=payment.orders_id and payment.cleared_time >0', 'left')->where('order.order_id', $value['order_id'])->find();
                
                $order['collection'] = $money = OrderModel::offer($value['order_id'])['amount'];
            } else {
                $order = null;
            }
            $message[$k]['old'] = 0;
            if($value['type']==51){
                $orderSetting = db('order_setting')->where(['order_id' => $value['order_id']])->find();
                if($orderSetting['stop_agent_reimbursement']==0){
                    $message[$k]['old']    = 1;
                }
            }
            $pattern = '/电话(\d{3})(\d{4})(\d{4})/';
            $replacement = '电话:$1****$3';
            // 替换电话号码
            $newText = preg_replace($pattern, $replacement, $value['content']);
            $messageInfo='';
            if($value['type']==61){
                $messageInfo=db('through')->where(['through_id' => $value['other_id']])->value('feedback');
            }
            $message[$k]['messageInfo']=$messageInfo;
            $message[$k]['content']=$newText;
            $message[$k]['order'] = $order;
        }
        r_date($message, 200);
    }
    
    /*
    * 1系统消息2订单提醒3订单跟进提醒4上门提醒5公司通知6新订单
    */
    public function message_info() {
        $data            = $this->model->post(['id']);
        $message         = db('message')->where('id', $data['id'])->field('type,content,order_id,already,time')->find();
        $message['time'] = date('Y-m-d H:i:s', $message['time']);
        if ($message['already'] != 0) {
            db('message')->where('id', $data['id'])->update(['already' => 0, 'have' => time()]);
        }
        
        r_date($message, 200);
    }
    
    /*
     * 储备店长
     */
    public function reserve() {
        $data   = $this->model->post();
        $chanel = db('user')->field('user.number,user.username,user.mobile,user.lat,user.lng,user.user_id');
        if (isset($data['username']) && $data['username'] != '') {
            $chanel->where(['user.username' => ['like', "%{$data['username']}%"]]);
        }
        $list = $chanel->where(['status' => 0, 'reserve' => 2, 'store_id' => $this->us['store_id']])->order('status')->select();
        r_date($list, 200);
    }
    
    /**
     * 获取后台客户注册的
     */
    public function jp() {
        $message = db('admin')->field('username,logo,admin_id')->where(['status' => 0, 'jp' => 1])->select();
        r_date($message, 200);
    }
    
    /**
     * 店铺
     * invoice_type
     */
    public function store() {
        $res = db('store')->field('store_id,store_name')->select();
        
        r_date($res, 200);
        
        
    }
    
    /**
     *工种
     * invoice_type
     */
    public function workType() {
        $res = Db::connect(config('database.db2'))->table('app_work_type')->whereNull('deleted_at')->where('status', 1)->field('id,title')->select();
        
        r_date($res, 200);
    }
    
    /*
     * 银行卡添加
     */
    public function bankCard() {
        
        $bank_card = \db('bank_card')->where('bank_card.delete_time', 0)->where(['user_id' => $this->us['user_id'], 'binding_uid' => $this->us['user_id']])->where('category', 1)->field('bank_card_number as bankCardNumber,account_name as accountName,bank_of_deposit as bankOfDeposit,bank_id as bankId,bank')->find();
        if (empty($bank_card)) {
            $list = ['bankCardNumber' => '', 'bankOfDeposit' => '', 'bankId' => (int)0, 'accountName' => ''];
        } else {
            $list = $bank_card;
        }
        r_date($list, 200);
    }
    
    public function addBankCard() {
        $data = Request::instance()->post();

//        if (!check_bankCard($data['bankCardNumber'])) {
//            r_date(null, 300, '请输入正确的银行卡号');
//        }
        
        if (isset($data['id']) && !empty($data['id']) != 0) {
            $res = db('bank_card')->where('bank_id', $data['id'])->where('category', 1)->update(['account_name' => $data['accountName'], 'bank_card_number' => $data['bankCardNumber'], 'bank_of_deposit' => $data['bankOfDeposit'], 'bank' => $data['bank'], 'revision_time' => time()]);
        } else {
            
            $res = db('bank_card')->insertGetId(['user_id' => $this->us['user_id'], 'account_name' => $data['accountName'], 'bank_card_number' => $data['bankCardNumber'], 'bank_of_deposit' => $data['bankOfDeposit'], 'type' => 2, 'creation_time' => time(), 'category' => 1, 'remarks' => '店长', 'binding_uid' => $this->us['user_id'], 'bank' => $data['bank']]);
        }
        if ($res) {
            r_date($data['bankCardNumber'], 200);
        } else {
            r_date(null, 300);
        }
    }
    
    public function collectionOtherAdd() {
        $data  = Request::instance()->post();
        $count = db('bank_card')->where('bank_card.delete_time', 0)->where(['bank_card_number' => $data['bankCardNumber']])->count();
        if ($count > 0) {
            r_date(null, 300, '这个银行卡有人已经录入，可以搜索姓名或者银行卡号调用');
        }
        //        if (!check_bankCard($data['bankCardNumber'])) {
        //            r_date(null, 300, '请输入正确的银行卡号');
        //        }
        
        $res = db('bank_card')->insertGetId(['user_id' => $this->us['user_id'], 'account_name' => $data['accountName'], 'bank_card_number' => $data['bankCardNumber'], 'bank_of_deposit' => $data['bankOfDeposit'], 'type' => $data['type'], 'creation_time' => time(), 'category' => 1, 'remarks' => $data['remarks'], 'bank' => $data['bank']]);
        
        if ($res) {
            $data['bankId'] = $res;
            r_date($data, 200);
        } else {
            r_date(null, 300);
        }
    }
    
    /*
     * val bankCardNumber: String?,
        val accountName: String?,
        val bankOfDeposit: String?,
        val remarks: String?,
        val type: String?,
        val bankId: Int?
     */
    public function searchBank() {
        $data = Request::instance()->post();
        $res  = db('bank_card')->where(function ($query) use ($data) {
            if ($data['accountName'] != '') {
                $query->whereOr('bank_card_number', 'Like', "%{$data['accountName']}%")->whereOr('account_name', 'Like', "%{$data['accountName']}%");
            }
            
        })->where('delete_time', 0)->field('bank_card_number as bankCardNumber,account_name as accountName,bank_of_deposit as bankOfDeposit,bank_id as bankId,remarks')->select();
        
        r_date($res, 200);
        
    }
    
    /*
     * 最近使用的
     */
    public function searchLatelBank() {
        
        $res = db('reimbursement_relation')->join('reimbursement', 'reimbursement_relation.reimbursement_id=reimbursement.id', 'left')->Join('bank_card', 'bank_card.bank_id=reimbursement_relation.bank_id', 'left')->where('reimbursement.user_id', $this->us['user_id'])->where('reimbursement.type', 1)->where('bank_card.delete_time', 0)->where('reimbursement.classification', 'neq', 4)->field('bank_card.bank_card_number as bankCardNumber,bank_card.remarks,bank_card.account_name as accountName,bank_card.bank_of_deposit as bankOfDeposit,bank_card.bank_id as bankId')->limit(0, 3)->group('bank_card.bank_card_number')->order('reimbursement.id desc')->select();
        r_date($res, 200);
        
    }
    
    /*
     * 联系人标签
     */
    
    public function contactLabel() {
        $data           = Authority::param(['order_id']);
        $telephone      = db('order')->where('order_id', $data['order_id'])->value('telephone');
        $labelList      = db('contact_label', config('database.zong'))->field('contacts_id,title,content,option')->where('status', 1)->select();
        $orderLabelList = db('order_contact_label', config('database.zong'))->where('telephone', $telephone)->whereNull('delete_time')->field('classification,order_id,contact_label')->select();
        $result         = array();
        $schemeTag      = array();
        foreach ($labelList as $k => $v) {
            $labelList[$k]['choice'] = 0;
            foreach ($orderLabelList as $item) {
                if ($v['contacts_id'] == $item['contact_label']) {
                    $labelList[$k]['choice'] = 1;
                }
            }
            
        }
        foreach ($labelList as $k => $v) {
            $result[$v['title']][] = $v;
        }
        foreach ($result as $k => $list) {
            $schemeTag['title']  = $k;
            $schemeTag['id']     = $list[0]['contacts_id'];
            $schemeTag['option'] = $list[0]['option'];
            $schemeTag['data']   = $result[$k];
            $tageList[]          = $schemeTag;
        }
        r_date(['labelList' => $tageList, 'orderLabelList' => $orderLabelList], 200);
    }
    
    
    public function contactLabelEdit() {
        $data                           = Authority::param(['contactLabelArray', 'order_id']);
        $contactLabelArray              = json_decode($data['contactLabelArray'], true);
        $contactLabelArrayOriginal      = [];
        $contactLabelArrayList          = [];
        $contactLabelArrayListCancelled = [];
        $alreadyCancelled               = [];
        $alreadyCancelledADD            = [];
        db()->startTrans();
        try {
            $telephone = db('order')->where('order_id', $data['order_id'])->value('telephone');
            foreach ($contactLabelArray as $list) {
                foreach ($list['data'] as $item) {
                    if ($item['isMyChoice'] == 0 && $item['choice'] == 1) {
                        //原来的
                        $contactLabelArrayOriginal[] = $item;
                    }
                    if ($item['isMyChoice'] == 1 && $item['choice'] == 0) {
                        //新增的
                        $contactLabelArrayList[] = $item;
                    }
                    if ($item['isCancel'] == 1 && $item['choice'] == 1) {
                        //新增的
                        $contactLabelArrayListCancelled[] = $item;
                    }
                    
                }
                
            }
            $already = [];
            foreach ($contactLabelArrayOriginal as $item) {
                foreach ($contactLabelArrayList as $value) {
                    if ($item['title'] == $value['title']) {
                        $opList['order_id']     = $data['order_id'];
                        $opList['created_time'] = time();
                        $opList['content']      = $item['title'] . $item['content'] . '标记为:' . $value['content'];
                        $opList['operation']    = $this->us['username'];
                        $opList['user_id']      = $this->us['user_id'];
                        $contact_label[]        = $item['contacts_id'];
                        $opList['role']         = 1;
                        $already[]              = $opList;
                    }
                }
                
            }
            foreach ($contactLabelArrayListCancelled as $l) {
                if (!empty($contactLabelArrayList)) {
                    foreach ($contactLabelArrayList as $value) {
                        if ($l['title'] != $value['title']) {
                            
                            $opListCancelled['order_id']     = $data['order_id'];
                            $opListCancelled['created_time'] = time();
                            $opListCancelled['content']      = $l['title'] . '取消了：' . $l['content'];
                            $opListCancelled['operation']    = $this->us['username'];
                            $opListCancelled['user_id']      = $this->us['user_id'];
                            $contact_labelList[]             = $l['title'];
                            $contact_labelListID[]           = $l['contacts_id'];
                            $opListCancelled['role']         = 1;
                            $alreadyCancelled[]              = $opListCancelled;
                            
                        }
                    }
                    
                } else {
                    $opListCancelled['order_id']     = $data['order_id'];
                    $opListCancelled['created_time'] = time();
                    $opListCancelled['content']      = $l['title'] . '取消了：' . $l['content'];
                    $opListCancelled['operation']    = $this->us['username'];
                    $opListCancelled['user_id']      = $this->us['user_id'];
                    $contact_labelList[]             = $l['title'];
                    $contact_labelListID[]           = $l['contacts_id'];
                    $opListCancelled['role']         = 1;
                    $alreadyCancelled[]              = $opListCancelled;
                }
                
                
            }
            $listArrayNew = [];
            foreach ($contactLabelArrayList as $item) {
                
                $listArray['order_id']       = $data['order_id'];
                $listArray['contact_name']   = $item['title'];
                $listArray['contact_label']  = $item['contacts_id'];
                $listArray['role']           = 1;
                $listArray['user_id']        = $this->us['user_id'];
                $listArray['created_time']   = time();
                $listArray['classification'] = $item['content'];
                $listArray['telephone']      = $telephone;
                $listArrayNew[]              = $listArray;
                if (!empty($contactLabelArrayOriginal)) {
                    foreach ($contactLabelArrayOriginal as $value) {
                        if ($item['title'] != $value['title']) {
                            $opListCancelledADD['order_id']     = $data['order_id'];
                            $opListCancelledADD['created_time'] = time();
                            $opListCancelledADD['content']      = $item['title'] . '标记为:' . $item['content'];
                            $opListCancelledADD['operation']    = $this->us['username'];
                            $opListCancelledADD['user_id']      = $this->us['user_id'];
                            $opListCancelledADD['role']         = 1;
                            $alreadyCancelledADD[]              = $opListCancelledADD;
                        }
                    }
                    
                } else {
                    $opListCancelledADD['order_id']     = $data['order_id'];
                    $opListCancelledADD['created_time'] = time();
                    $opListCancelledADD['content']      = $item['title'] . '标记为:' . $item['content'];
                    $opListCancelledADD['operation']    = $this->us['username'];
                    $opListCancelledADD['user_id']      = $this->us['user_id'];
                    $opListCancelledADD['role']         = 1;
                    $alreadyCancelledADD[]              = $opListCancelledADD;
                }
                
                
            }
            
            if (!empty($already)) {
                db('order_contact_label_logo', config('database.zong'))->insertAll($already);
                db('order_contact_label', config('database.zong'))->where('order_id', $data['order_id'])->whereIn('contact_label', array_unique($contact_label))->update(['delete_time' => time()]);
                
            }
            if (!empty($alreadyCancelled)) {
                db('order_contact_label_logo', config('database.zong'))->insertAll($alreadyCancelled);
                db('order_contact_label', config('database.zong'))->where('order_id', $data['order_id'])->whereIn('contact_label', $contact_labelListID)->update(['delete_time' => time()]);
            }
            if (!empty($alreadyCancelledADD)) {
                $alreadyCancelledADD = $this->assoc_unique($alreadyCancelledADD, 'content');
                db('order_contact_label_logo', config('database.zong'))->insertAll($alreadyCancelledADD);
            }
            
            
            if (!empty($listArrayNew)) {
                db('order_contact_label', config('database.zong'))->insertAll($listArrayNew);
            }
            db()->commit();
            r_date(null, 200);
            
        } catch (Exception $e) {
            db()->rollback();
            r_date([], 300, $e->getMessage());
        }
        
        
    }
    
    public function OrderContactLabelLogo() {
        $data      = Authority::param(['order_id']);
        $telephone = db('order')->where('order_id', $data['order_id'])->value('telephone');
        $logo      = db('order_contact_label_logo', config('database.zong'))->join('order_contact_label', 'order_contact_label.order_id=order_contact_label_logo.order_id', 'left')->where('telephone', $telephone)->field('FROM_UNIXTIME(order_contact_label_logo.created_time,"%Y-%m-%d %H:%i:%s") as created_time,CONCAT(CASE order_contact_label_logo.role WHEN 1 THEN "店长"WHEN 2 THEN "客服"WHEN 3 THEN "后台" END ,order_contact_label_logo.operation) as operation,order_contact_label_logo.content')->group('content')->order('created_time desc')->select();
        $tageList  = [];
        if (!empty($logo)) {
            foreach ($logo as $k => $v) {
                $result[$v['created_time']][] = $v;
            }
            foreach ($result as $k => $list) {
                $schemeTag['created_time'] = $k;
                $schemeTag['operation']    = $list[0]['operation'];
                $schemeTag['data']         = $result[$k];
                $tageList[]                = $schemeTag;
            }
        }
        
        r_date($tageList, 200);
    }
    
    /*
     * 二维数组去重
     */
    
    public function assoc_unique($arr, $key) {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
                unset($arr[$k]);
            } else {
                $tmp_arr[] = $v[$key];
            }
        }
        sort($arr); //sort函数对数组进行排序
        return $arr;
    }
    
    /*
     * 修改用户姓名
     */
    public function modifyUserName() {
        $data = Authority::param(['orderId', 'contacts']);
        \db('order')->where('order_id', $data['orderId'])->update(['contacts' => $data['contacts']]);
        r_date(null, 200);
    }
    
    /*
   * 生成二维码
   */
    public function RecommendationCode(Common $common) {
        $list = $common->personalName($this->us, \config('cityId'));
        r_date($list, 200);
        
    }
    
    /*
    * 店长积分详情
    */
    public function pointsInfo() {
        $list  = Db::connect(config('database.zong'))->table('behavior_score')->join('user', 'user.user_id=behavior_score.user_id', 'left')->field('sum(behavior_score.behavior_score) as score,behavior_score.user_id,user.avatar')->group('user_id')->where('user_type', 1)->order('score desc')->where('user.ce', 1)->whereNotLike('user.username', "%代管%")->where('behavior_score.delete_time', 0)->select();
        $my    = null;
        $three = [];
        foreach ($list as $k => $v) {
            $list[$k]['sequence'] = $k + 1;
            if ($v['user_id'] == $this->us['user_id']) {
                $my = $list[$k];
            }
            if ($list[$k]['sequence'] == 1 || $list[$k]['sequence'] == 2 || $list[$k]['sequence'] == 3 || $list[$k]['sequence'] == 4 || $list[$k]['sequence'] == 5) {
                $three[] = $list[$k];
            }
        }
        $content                   = \db('config')->where('name', 'behavior_score')->value('content');
        $content                   = json_decode($content, true);
        $UserBehaviorScore         = [];
        $CustomerSatisfactionScore = [];
        foreach ($content as $k => $value) {
            
            $title                = self::behaviorTitle($content[$k]['behavior']);
            $content[$k]['title'] = $title;
            if ($content[$k]['behavior'] == 1 || $content[$k]['behavior'] == 2 || $content[$k]['behavior'] == 3 || $content[$k]['behavior'] == 4 || $content[$k]['behavior'] == 5 || $content[$k]['behavior'] == 6 || $content[$k]['behavior'] == 9) {
                $titleContent[]    = $content[$k];
                $UserBehaviorScore = ['title' => '一、用户行为分', 'content' => $titleContent];
            }
            if ($content[$k]['behavior'] == 7 || $content[$k]['behavior'] == 8) {
                $title1[]                  = $content[$k];
                $CustomerSatisfactionScore = ['title' => '一、用户满意分', 'content' => $title1];
            }
            unset($content[$k]['relation_table']);
        }
        $SatisfactionScore = [];
        array_push($SatisfactionScore, $UserBehaviorScore);
        array_push($SatisfactionScore, $CustomerSatisfactionScore);
        if (empty($my)) {
            $title = "-";
        } else {
            $title = "积分排行榜:" . $my['sequence'] . "/" . count($list);
        }
        r_date(['me' => empty($my) ? ['score' => 0, 'avatar' => "", "sequence" => 0] : $my, 'three' => $three, 'title' => $title, 'BehaviorScore' => $SatisfactionScore], 200);
    }
    
    public function pointsDetails() {
        $data  = Authority::param(['type', 'searchTimeStare', 'searchTimeEnd']);
        $query = Db::connect(config('database.zong'))->table('behavior_score')->field('behavior_score.user_id,behavior_score.behavior_type,behavior_score.order_id as orderId,order.order_no,behavior_score.behavior_score as score,FROM_UNIXTIME(behavior_score.behavior_time, "%Y-%m-%d %H:%i" ) AS stareTime')->join('order', 'order.order_id=behavior_score.order_id', 'left')->where('behavior_score.user_id', $this->us['user_id']);
        if ($data['searchTimeStare'] != 0 && $data['searchTimeEnd'] != 0) {
            $query->whereBetween('behavior_score.behavior_time', [strtotime($data['searchTimeStare']), strtotime($data['searchTimeEnd']) + 86400]);
        }
        //用户行为分
        if ($data['type'] == 1) {
            $query->whereIn('behavior_score.behavior_type', [1, 2, 3, 4, 5, 6, 9]);
            
            //用户满意分
        } elseif ($data['type'] == 2) {
            $query->whereIn('behavior_score.behavior_type', [7, 8]);
            
        } elseif ($data['type'] == 0) {
            $query->whereIn('behavior_score.behavior_type', [1, 2, 3, 4, 5, 6, 7, 8, 9]);
            
        }
        $behavior_score = $query->where('behavior_score.user_type', 1)->where('behavior_score.delete_time', 0)->select();
        foreach ($behavior_score as $k => $value) {
            $title = self::behaviorTitle($behavior_score[$k]['behavior_type'], 2);
//            if($value['score']>0){
//                $behavior_score[$k]['score'] = '+'.$value['score'];
//            }
            $behavior_score[$k]['title'] = $title;
        }
        r_date($behavior_score);
    }
    
    public static function behaviorTitle($behavior, $type = 1) {
        switch ($behavior) {
            case 1:
                $title  = "1、设置关键工序排期【行为分】";
                $title1 = "设置关键工序排期【行为分】";
                break;
            case 2:
                $title  = "2、上传图文施工交接【行为分】";
                $title1 = "上传图文施工交接【行为分】";
                break;
            case 3:
                $title  = "3、上传排期内关键工序节点施工内容【行为分】";
                $title1 = "上传排期内关键工序节点施工内容【行为分】";
                break;
            case 4:
                $title  = "4、上传符合标准的完工素材【行为分】";
                $title1 = "上传符合标准的完工素材【行为分】";
                break;
            case 5:
                $title  = "5、上传图文施工交接【行为分】";
                $title1 = "上传图文施工交接";
                break;
            case 6:
                $title  = "6、上传符合标准的完工素材【行为分】";
                $title1 = "上传符合标准的完工素材";
                break;
            case 7:
                $title  = "1、项目用户分享【用户分】";
                $title1 = "项目用户分享【用户分】";
                break;
            case 8:
                $title  = "2、投诉【用户分】";
                $title1 = "投诉【用户分】";
                break;
            case 9:
                $title  = "7、完工验收图片审核通过【行为分】";
                $title1 = "完工验收图片审核通过【行为分】";
                break;
            
            default:
                $title  = "";
                $title1 = "";
        }
        if ($type == 1) {
            return $title;
        } else {
            return $title1;
        }
        
    }
    
    /*
     * 店长师傅行为分统计表
     */
    public function userScore() {
        $data  = Authority::param(['cityId', 'type', 'storeId']);
        $query = Db::connect(config('database.zong'))->table('behavior_score')->field('behavior_score.user_id,user.username,user.avatar,sum(behavior_score.behavior_score) as score,store.store_name as storeName,FROM_UNIXTIME( behavior_score.behavior_time, "%Y-%m" ) AS month,FROM_UNIXTIME(behavior_score.behavior_time, "%Y" ) AS year')->join('city', 'city.city_id=behavior_score.city_id', 'left')->join('user', 'user.user_id=behavior_score.user_id', 'left')->join('store', 'store.store_id=user.store_id', 'left');
        if ($data['cityId'] != 0) {
            $query->where('behavior_score.city_id', $data['cityId']);
        }
        if ($data['storeId'] != 0) {
            $query->where('user.store_id', $data['storeId']);
        }
        //年榜
        if ($data['type'] == 1) {
            $year = strtotime(date('Y-01-01 00:00:00', time()));
            $query->whereBetween('behavior_score.behavior_time', [$year, time()]);
            $query->group('year');
            $query->order('score desc');;
            //月榜
        } elseif ($data['type'] == 2) {
            $firstDay = strtotime(date('Y-m-01 00:00:00', time()));
            $lastDay  = strtotime(date('Y-m-d 23:59:59', strtotime(date('Y-m-01', time()) . ' 1 month -1 day')));
            $query->whereBetween('behavior_score.behavior_time', [$firstDay, $lastDay]);
            $query->group('month');
            $query->order('score desc');;
        } elseif ($data['type'] == 3) {
            //总榜
            $query->order('score desc');
        }
        $behavior_score = $query->where('behavior_score.user_type', 1)->where('user.ce', 1)->whereNotLike('user.username', "%代管%")->where('behavior_score.delete_time', 0)->group('behavior_score.user_id')->select();
        $my             = null;
        
        $three    = [];
        $followUp = [];
        foreach ($behavior_score as $k => $v) {
            $behavior_score[$k]['sequence'] = $k + 1;
            unset($behavior_score[$k]['month'], $behavior_score[$k]['year']);
            if ($v['user_id'] == $this->us['user_id']) {
                $my = $behavior_score[$k];
            }
            if ($behavior_score[$k]['sequence'] == 1 || $behavior_score[$k]['sequence'] == 2 || $behavior_score[$k]['sequence'] == 3) {
                $three[] = $behavior_score[$k];
            } else {
                $followUp[] = $behavior_score[$k];
            }
        }
        r_date(['three' => $three, 'list' => $followUp, 'my' => $my], 200);
    }
    
    /*
  * 店长师傅行为分统类型
  */
    public function userScoreType() {
        $list = [['type' => 0, 'title' => "全部",], ['type' => 1, 'title' => "用户行为分",], ['type' => 2, 'title' => "用户满意分",]];
        r_date($list, 200);
    }
    
    /*
     * 我的接单范围
     */
    public function receivingOrders() {
        $query     = Db::connect(config('database.zong'))->table('dispatch_config_user')->field('dispatch_config_user.dedicated_task,dispatch_config_user.partial_renovation_switch,dispatch_config_user.partial_renovation_preset,dispatch_config_user.waterproof_repair_switch,dispatch_config_user.waterproof_repair_preset,dispatch_config_user.wall_renovation_switch,dispatch_config_user.wall_renovation_preset,dispatch_config_user.maintenance_installation_switch,dispatch_config_user.maintenance_installation_preset,
            group_concat(distinct dispatch_config_district.name) as address,group_concat(distinct dispatch_config_user_chanel.chanel_id) as chanelId,dispatch_config_user.dispatch_level')->join('dispatch_config_user_chanel', 'dispatch_config_user_chanel.user_id=dispatch_config_user.user_id', 'left')->join('dispatch_config_user_district', 'dispatch_config_user_district.user_id=dispatch_config_user.user_id', 'left')->join('dispatch_config_district', 'dispatch_config_district.id=dispatch_config_user_district.district_id', 'left')->where('dispatch_config_user.user_id', $this->us['user_id'])->group('dispatch_config_user.user_id')->find();
        $userLeve  = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'user_level_dispatch_limit')->whereNull('delete_time')->find();
        $month     = monthBetween();
        $userLimit = Db::connect(config('database.zong'))->table('user_dispatch_log')->join('order', 'order.order_id=user_dispatch_log.order_id', 'left')->where('user_id', $this->us['user_id'])->where('action_type', 1)->where('add_type', '<>', 4)->field('sum(if(add_type=2,action_quantity,0)) as reverseConversion,sum(if(add_type=3 and order.assignor=' . $this->us['user_id'] . ',action_quantity,0)) as hematopoiesis')->whereBetween('create_time', [$month['first'], $month['last']])->select();
        $firstDayOfLastMonth = strtotime(date('Y-m-01 00:00:00', strtotime('last month')));

// 获取上个月最后一天
        $lastDayOfLastMonth = strtotime(date('Y-m-t 23:59:59', strtotime('last month')));
        $dispatch_config_user_dispatch_level_log= Db::connect(config('database.zong'))->table('dispatch_config_user_dispatch_level_log')->where('user_id', $this->us['user_id'])->whereBetween('create_time', [$firstDayOfLastMonth, $lastDayOfLastMonth])->sum('performance_bonus_quantity');
        $userInfo  = json_decode($userLeve['valuess'], true);
        //基础接单量
        $dispatch_level = 0;
        foreach ($userInfo as $l) {
            if (config('cityId') == $l['city_id']) {
                foreach ($l['limit'] as $k => $value) {
                    if ($k == $query['dispatch_level']) {
                        $dispatch_level = $value;
                    }
                }
                
            }
        }
        $performance                     = $dispatch_config_user_dispatch_level_log;
        $reverseConversion               = empty($userLimit[0]['reverseConversion']) ? 0 : $userLimit[0]['reverseConversion'];
        $hematopoiesis                   = empty($userLimit[0]['hematopoiesis']) ? 0 : $userLimit[0]['hematopoiesis'];
        $limit                           = db('order')->join('message', 'message.order_id=order.order_id and message.type=6', 'left')->where('order.state', '<>', 10)->where(function ($quer) {
            $quer->where('order.assignor', $this->us['user_id'])->whereOr('order.deliverer', $this->us['user_id']);
        })->whereBetween('message.time', [$month['first'], $month['last']])->group('order.order_id')->count();
        $channel_details                 = \db('channel_details')->field('concat(chanel.title,"/",channel_details.title) as title')->join('chanel', 'chanel.id=channel_details.pid', 'left')->whereIn('channel_details.id', $query['chanelId'])->select();
        $zeroTimestamp                   = strtotime(date('Y-m-d', time()));
        $orderCount                      = Db::connect(config('database.zong'))->table('order')->where('assignor', $this->us['user_id'])->where('state', '<>', 10)->field('count("pro_id") as countProId,pro_id as proId')->where('created_time', '<', $zeroTimestamp)->group('pro_id')->select();
        $partial_renovation_preset       = !empty(floatval($query['partial_renovation_preset'])) ? ($query['partial_renovation_preset'] * 100) . "%(预设值)" : "-";//"局部改造预设成交率 3
        $waterproof_repair_preset        = !empty(floatval($query['waterproof_repair_preset'])) ? ($query['waterproof_repair_preset'] * 100) . "%(预设值)" : "-";//防水补漏预设成交率" 42
        $wall_renovation_preset          = !empty(floatval($query['wall_renovation_preset'])) ? ($query['wall_renovation_preset'] * 100) . "%(预设值)" : "-";//"墙面翻新成预设成交率"  1
        $maintenance_installation_preset = !empty(floatval($query['maintenance_installation_preset'])) ? ($query['maintenance_installation_preset'] * 100) . "%(预设值)" : "-";//维修安装预设成交率 104
        foreach ($orderCount as $i) {
            $deal_rate = Db::table('shp_mgr_deal_rate')->where('user_id', $this->us['user_id'])->where('pro_id', $i['proId'])->value('deal_rate') * 100;
            if ($i['proId'] == 1 && $i['countProId'] >= 10) {
                $wall_renovation_preset = $deal_rate . "%";
            } elseif ($i['proId'] == 3 && $i['countProId'] >= 10) {
                $partial_renovation_preset = $deal_rate . "%";
            } elseif ($i['proId'] == 42 && $i['countProId'] >= 10) {
                $waterproof_repair_preset = $deal_rate . "%";
            } elseif ($i['proId'] == 104 && $i['countProId'] >= 10) {
                $maintenance_installation_preset = $deal_rate . "%";
            }
            
        }
        $channel_details = empty($channel_details) ? '' : implode("\n", array_column($channel_details, 'title'));
        $address         = empty($query['address']) ? '' : implode("\n", explode(",", $query['address']));
        $dedicated_task  = "普通渠道";
        if ($query['dedicated_task'] == 1) {
            $dedicated_task = "专人专项";
        }
        
        $partial_renovation_switch     = "关闭";
        $partial_renovation_switchList = [['title' => "局部改造权限", 'list' => $partial_renovation_switch]];
        if ($query['partial_renovation_switch'] == 1) {
            $partial_renovation_switch     = "开启";
            $partial_renovation_switchList = [['title' => "局部改造权限", 'list' => $partial_renovation_switch], ['title' => "局部改造成交率", 'list' => $partial_renovation_preset],];
        }
        $waterproof_repair_switch     = "关闭";
        $waterproof_repair_switchList = [['title' => "防水补漏权限", 'list' => $waterproof_repair_switch]];
        if ($query['waterproof_repair_switch'] == 1) {
            $waterproof_repair_switch     = "开启";
            $waterproof_repair_switchList = [['title' => "防水补漏权限", 'list' => $waterproof_repair_switch], ['title' => "防水补漏成交率", 'list' => $waterproof_repair_preset]];
        }
        $wall_renovation_switch     = "关闭";
        $wall_renovation_switchList = [['title' => "墙面翻新权限", 'list' => $wall_renovation_switch]];
        if ($query['wall_renovation_switch'] == 1) {
            $wall_renovation_switch     = "开启";
            $wall_renovation_switchList = [['title' => "墙面翻新权限", 'list' => $wall_renovation_switch], ['title' => "墙面翻新成交率", 'list' => $wall_renovation_preset]];
        }
        $maintenance_installation_switch     = "关闭";
        $maintenance_installation_switchList = [['title' => "维修安装权限", 'list' => $maintenance_installation_switch]];
        if ($query['maintenance_installation_switch'] == 1) {
            $maintenance_installation_switch     = "开启";
            $maintenance_installation_switchList = [['title' => "维修安装权限", 'list' => $maintenance_installation_switch], ['title' => "维修安装成交率", 'list' => $maintenance_installation_preset]];
        }
        $combinedData              = array_merge($partial_renovation_switchList, $waterproof_repair_switchList, $wall_renovation_switchList, $maintenance_installation_switchList);
        $dispatch_config_blacklist = Db::connect(config('database.zong'))->table('channel_details')->join('dispatch_config_blacklist', 'dispatch_config_blacklist.chanel_id=channel_details.id', 'left')->join('chanel', 'chanel.id=channel_details.pid', 'left')->where('dispatch_config_blacklist.user_id', $this->us['user_id'])->where('dispatch_config_blacklist.city_id', config('cityId'))->field('concat(chanel.title,"/",channel_details.title) as title')->select();
//        $combinedData = [
//            ['title' => "局部改造权限", 'list' => $partial_renovation_switch],
//            ['title' => "局部改造成交率", 'list' => $partial_renovation_preset],
//            ['title' => "防水补漏权限", 'list' => $waterproof_repair_switch],
//            ['title' => "防水补漏成交率", 'list' => $waterproof_repair_preset],
//            ['title' => "墙面翻新权限", 'list' => $wall_renovation_switch],
//            ['title' => "墙面翻新成成交率", 'list' => $wall_renovation_preset],
//            ['title' => "维修安装权限", 'list' => $maintenance_installation_switch],
//            ['title' => "维修安装成交率", 'list' => $maintenance_installation_preset]
//        ];
        
        $get_order = "接单";
        if ($this->us['get_order'] == 0) {
            $get_order = "停单";
        }
        $data['orderStatus'] = ['title' => "接单状态", 'list' => $get_order];
        
        $data['classification'] = [['title' => "我的接单量数据", 'data' => [['title' => "本月总计可接单量:", 'list' => ($dispatch_level + $performance + $reverseConversion + $hematopoiesis)], ['title' => "基础接单量:", 'list' => $dispatch_level], ['title' => "业绩奖励接单量:", 'list' => $performance], ['title' => "复转奖励接单量:", 'list' => $reverseConversion], ['title' => "造血订单奖励:", 'list' => $hematopoiesis], ['title' => "本月已接单量:", 'list' => $limit]]], ['title' => "业务接单权限", 'data' => $combinedData], ['title' => "渠道接单权限", 'data' => [['title' => "渠道分类", 'list' => $dedicated_task], ['title' => "渠道权限", 'list' => $channel_details], ['title' => "纳入黑名单", 'list' => implode('、', array_column($dispatch_config_blacklist, 'title'))]]], ['title' => "商圈接单权限", 'data' => [['title' => "商圈权限", 'list' => $address]]]
        
        ];
        if ($this->us['get_order'] == 0) {
            $data['classification'] = [['title' => "我的接单量数据", 'data' => [['title' => "本月总计可接单量:", 'list' => ($dispatch_level + $performance + $reverseConversion + $hematopoiesis)], ['title' => "基础接单量:", 'list' => $dispatch_level], ['title' => "业绩奖励接单量:", 'list' => $performance], ['title' => "复转奖励接单量:", 'list' => $reverseConversion], ['title' => "造血订单奖励:", 'list' => $hematopoiesis], ['title' => "本月已接单量:", 'list' => $limit]]]];
            
        }
        
        r_date($data, 200);
    }
    
    /*
     * ai
     */
    public function aiPlus() {
        $url = 'https://aigc.yiniao.co/';
        r_date($url, 200);
    }
    
    /*
     * ai图片上传
     */
    public function aiPlusAdd(Common $common) {
        $data = Authority::param(['orderId', 'img']);
        $common->MultimediaResources($data['orderId'], $this->us['user_id'], !empty($data['img']) ? json_decode($data['img'], true) : [], 5);
        r_date(null, 200);
    }
    
    /*
     * 获取店铺
     */
    public function cityOpen() {
        $cityOpen = Db::connect(config('database.zong'))->table('city_open')->join('store', 'store.city=city_open.city_id')->field('group_concat(store.store_name,"-",store.store_id) as store_name,city_open.city_name as cityName,city_open.city_id as cityId')->where('store.status', 1)->where('city_open.status', 1)->group('city_open.city_id')->select();
        foreach ($cityOpen as $k => $item) {
            $p     = [];
            $store = explode(",", $item['store_name']);
            foreach ($store as $o) {
                $store = explode("-", $o);
                $p[]   = ['storeName' => $store[0], 'storeId' => $store[1],];
            }
            $cityOpen[$k]['store'] = $p;
            unset($cityOpen[$k]['store_name']);
        }
        
        r_date($cityOpen, 200);
    }
    
    public function inverseAnalysis() {
        $data     = Authority::param(['lng', 'lat']);
        $response = inverseAnalysis($data['lng'], $data['lat']);
        $response = json_decode($response, true);
        
        if (isset($response['status']) && $response['status'] == 0) {
            $list = $response['result'];
            r_date($list, 200);
        } else {
            r_date(null, 300, $response['msg']);
        }
        
    }
    
    /*
   * 发票信息添加
   */
    public function invoiceAdd() {
        $data = Request::instance()->post();
      
        if ($data['invoiceTitle'] == '') {
            r_date(null, 300, '抬头名称不能为空');
        }
        if ($data['orderId'] == '' || !isset($data['orderId']) || $data['orderId'] == 0) {
            r_date(null, 300, '订单id不能为空');
        }
        if (!is_email($data['invoiceEmail'])) {
            r_date(null, 300, '请填写正确的邮箱');
        }
        if ($data['invoiceType'] == 2) {
            if ($data['invoiceTaxCode'] == '') {
                r_date(null, 300, '税号不能为空');
            }
        }
        if ($data['invoiceType'] == 3) {
            if ($data['invoiceTaxCode'] == '') {
                r_date(null, 300, '税号不能为空');
            }
            if ($data['invoiceBankName'] == '') {
                r_date(null, 300, '开户行不能为空');
            }
            if ($data['invoiceBankAccount'] == '') {
                r_date(null, 300, '公司银行账号不能为空');
            }
        }
        $l             = ['invoice_type' => $data['invoiceType'], //'发票抬头类型 1：个人票 2：公司普票 3：公司专票',
            'invoice_title' => $data['invoiceTitle'], //'发票抬头名称',
            'invoice_email' => $data['invoiceEmail'],//'接收发票的邮箱地址',
            'invoice_tax_code' => isset($data['invoiceTaxCode']) ? $data['invoiceTaxCode'] : '',//'发票公司税号',
            'invoice_company_address' => isset($data['invoiceCompanyAddress']) ? $data['invoiceCompanyAddress'] : '', //'发票公司注册地址',
            'invoice_company_phone' => isset($data['invoiceCompanyPhone']) ? $data['invoiceCompanyPhone'] : '', //'发票公司注册电话',
            'invoice_bank_name' => isset($data['invoiceBankName']) ? $data['invoiceBankName'] : '', //'发票公司开户行',
            'invoice_bank_account' => isset($data['invoiceBankAccount']) ? $data['invoiceBankAccount'] : '',//'发票公司银行账号',
            'create_time' => time(), //'创建时间',
        ];
        $order_invoice = Db::connect(config('database.zong'))->table('order_invoice')->where('order_id', $data['orderId'])->find();
        if ($order_invoice) {
            Db::connect(config('database.zong'))->table('order_invoice')->where('order_id', $data['orderId'])->update($l);
            $invoice_title=$this->us['username'].'更新了发票信息';
            $order_invoice_id=$order_invoice['id'];
            $invoice_old_json=json_encode($order_invoice);
        } else {
            $l['order_id'] = $data['orderId'];//'订单ID（关联order表order_id字段）',
            $order_invoice=Db::connect(config('database.zong'))->table('order_invoice')->insertGetId($l);
            $invoice_title=$this->us['username'].'新增了发票信息';
            $invoice_old_json='';
            $order_invoice_id=$order_invoice;
        }
        Db::connect(config('database.zong'))->table('order_invoice_log')->insert(['invoice_title'=>$invoice_title,'order_invoice_id'=>$order_invoice_id,'user_id'=>$this->us['user_id'],'invoice_old_json'=>$invoice_old_json,'invoice_json'=>json_encode($l),'create_time'=>time()]);
        r_date(null, 200);
    }
    
    public function invoiceInfo() {
       
        $data          = Authority::param(['orderId']);
        $order_invoice = Db::connect(config('database.zong'))->table('order_invoice')->where('order_id', $data['orderId'])->field('invoice_type as invoiceType,invoice_title as invoiceTitle, invoice_email as invoiceEmail,invoice_tax_code as invoiceTaxCode,invoice_company_address as invoiceCompanyAddress,invoice_company_phone as invoiceCompanyPhone,invoice_bank_name as invoiceBankName,invoice_bank_account as invoiceBankAccount')->find();
        r_date($order_invoice, 200);
    }
}